/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_httpd.htm
 *
 * Zhiqim Httpd is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.httpd.util;

import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map.Entry;

import org.zhiqim.httpd.HttpResponse;
import org.zhiqim.httpd.context.ZmlContextConstants;

import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.logging.Log;

/**
 * 对HttpResponse进行一级封装，实现相关的数据提取工具类，分隔HttpResponse代码
 * 
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
@AnAlias("Responses")
public class Responses implements ZmlContextConstants
{
    /** 
     * 根据模式类型发送响应
     * 
     * @param response          响应
     * @param mode              响应模式,=1表示按内容发送，!=1表示按消息头发送
     * @param headerMap         消息头列表
     * @throws Exception        可能的异常
     */
    public static void doReturnMessage(HttpResponse response, int mode, HashMap<String, String> headerMap) throws IOException
    {
        if (mode != 1)
        {//默认采用头响应
            for (Entry<String, String> entry : headerMap.entrySet())
            {
                response.addHeader(entry.getKey(), entry.getValue());
            }
            response.sendHeader(_200_OK_);
        }
        else
        {//指定采用JSON响应
            response.setContentType(_TEXT_PLAIN_UTF_8_);
            StringBuilder strb = new StringBuilder("{");
            for (Entry<String, String> entry : headerMap.entrySet())
            {
                strb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"").append(",");
            }
            
            strb.setLength(strb.length()-1);
            strb.append("}");
            response.print(strb.toString());
            response.commit();
        }
    }
    
    /**
     * 输出并提交
     * 
     * @param response          响应
     * @param strb              字符串
     * @param log               日志
     * @throws SocketException  Socket异常抛出，其他异常打日志
     */
    public static void printAndCommit(HttpResponse response, StringBuilder strb, Log log) throws SocketException
    {
        try
        {
            response.print(strb.toString());
            response.commit();
        }
        catch(SocketException e)
        {//写入数据时，Socket异常，如对方中断，浏览器终止等，不打日志
            throw e;
        }
        catch(Exception e)
        {
            log.error(e);
        }
    }
}
